//
//  PhotoViewController.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/19.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit
import SVProgressHUD

// cell 标识
private let photocellID = "photocell"

class PhotoViewController: UIViewController, UICollectionViewDataSource {
    // 高清的图组
    var imageUrls:[NSURL]? {
        didSet{
            self.collView.reloadData()
        }
    }
    
    // 选中列
    var selectedIndex = 0
    
    // 布局
    lazy var layout: UICollectionViewLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        return layout;
    }()
    
    // 懒加载collection视图
    lazy var collView:UICollectionView = {
        let coll = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: self.layout)
        coll.showsHorizontalScrollIndicator = false
        coll.pagingEnabled = true
        coll.dataSource = self
        
        return coll
    }()
    
    
    
    // 加载全部视图
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        view.addSubview(collView)
        
        // 添加按钮
        let closeBtn:UIButton = createbtn("关闭")
        closeBtn.addTarget(self, action:"close", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(closeBtn)
        
        let saveBtn:UIButton = createbtn("保存")
        saveBtn.addTarget(self, action:"save", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(saveBtn)
        
        
        // 关掉autoresizing
        closeBtn.setTranslatesAutoresizingMaskIntoConstraints(false)
        saveBtn.setTranslatesAutoresizingMaskIntoConstraints(false)
        
        // 添加约束    VLF语言
        // 此方法返回的是数组
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[closeBtn(80)]-8-[saveBtn(80)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn":closeBtn,"saveBtn": saveBtn])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:[closeBtn]-20-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn": closeBtn])
        
        
        /**
            item:       对那个对象添加约束
            attribute:  约束属性
            relatedBy:  条件
            toItem:     相对于对象
            attribute:  相对对象的约束
            multiplier: 倍数
            constant:   偏移量
        */
        var cons2 = NSLayoutConstraint(item: saveBtn, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: closeBtn, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
        cons.append(cons2)
        
        // 外部约束添加到父视图中
        view.addConstraints(cons)
        
    }
    
    // 创建按钮
    private func createbtn(title: String) -> UIButton {
        let btn = UIButton()
        btn.setTitle(title, forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.grayColor()
        btn.alpha = 0.5
        
        return btn
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    func save() {
        println("保存图像")
        let cell = collView.visibleCells().last as! LargePicCell
        if let img = cell.mylargeVC?.largeImage {
            
            // 注意保存 到相册中,一定实现的方法必须是这个样子
            UIImageWriteToSavedPhotosAlbum(img, self, "image:didFinishSavingWithError:contextInfo:", nil)
        }
    }
    
    // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    // 实现方法
    func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
        if (didFinishSavingWithError != nil) {
            SVProgressHUD.showErrorWithStatus("保存失败", maskType: SVProgressHUDMaskType.Clear)
            return
        }
        SVProgressHUD.showSuccessWithStatus("保存成功", maskType: SVProgressHUDMaskType.Clear)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //注册cell
        self.collView.registerClass(LargePicCell.self, forCellWithReuseIdentifier: photocellID)
        
        // 滚动到视图
        let index = NSIndexPath(forItem: selectedIndex, inSection: 0)
        self.collView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.None, animated: false)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK: - 数据源代理
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell: LargePicCell = collectionView.dequeueReusableCellWithReuseIdentifier(photocellID, forIndexPath: indexPath) as! LargePicCell
        cell.imageUrl = self.imageUrls![indexPath.item] as NSURL
        
        /**
        *   添加子控制,一定要添加,切记
        *   添加子控制,一定要添加,切记
        *   添加子控制,一定要添加,切记
        *   添加子控制,一定要添加,切记
        *   添加子控制,一定要添加,切记
        */
        if !(childViewControllers as NSArray).containsObject(cell.mylargeVC!) {
            addChildViewController(cell.mylargeVC!)
        }
        return cell
    }
    
}





// MARK: 单张图片视图
class LargePicCell: UICollectionViewCell {
    var mylargeVC: LargePicController?
    
    var imageUrl: NSURL? {
        didSet {
            mylargeVC!.largeUrl = imageUrl
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        mylargeVC = LargePicController()
        mylargeVC?.view.frame = bounds
        addSubview(mylargeVC!.view)
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}
